//
//  STComposeController.swift
//  STVVeibo
//
//  Created by leergou on 16/7/26.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit
import SVProgressHUD

class STComposeController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupNav()
    }
    
    //MARK: setupUI
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
        // 添加子控件
        view.addSubview(composeTextView)
        composeTextView.addSubview(pictureView)
        view.addSubview(bottomToolBar)
        
        // 添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(composeTextView).offset(100)
            make.centerX.equalTo(composeTextView)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }
        
        bottomToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        //MARK: 底部工具条按钮监听事件 -> 闭包的实现
        bottomToolBar.closure = {[weak self] (type: STComposeBottomToolBarViewType)->() in
            switch type{
            case .Picture:
//                print("图片")
                // 打开相册
                self?.openAlbulm()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
//                print("表情")
                //在这里实现系统键盘和自定义键盘的切换
                self?.switchKeyboard()
            case .Add:
                print("+")
            }
        }
        //监听配图中 + 号cell 点击,弹出相册
        pictureView.closure = {[weak self] in
            self?.openAlbulm()
        }
        // 添加通知 -> 收到表情按钮点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonsClick:", name: EmoticonButtonsClick, object: nil)
        
        // 添加通知 --> 表情键盘,删除按钮点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButtonClick", name: EmoticonDeleteButtonClick, object: nil)
        // 添加通知 --> 监听键盘弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //MARK: 收到表情按钮点击通知调用的方法
    func emoticonButtonsClick(noti: NSNotification){
        //        print(noti.object)
        // 首先判断是否是 nil,而且是否可以转成 Emoticon 模型
        guard let emoticon = noti.object as? STEmoticon else {
            return
        }
        
//        print(emoticon.isSTEmoji)
        
        // 判断是否是 emoji 表情
        if emoticon.isSTEmoji {
            // 是 emoji 表情,将十六进格式转成制字符串
            let codeStr = (emoticon.code ?? "" as NSString).emoji()
//            print(codeStr)
            composeTextView.insertText(codeStr)
        } else {
            // 是 图片表情
            // 获取当前 composeTextView 的富文本
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            // 便利构造函数创建富文本
            // 参数
            let lineHeight = composeTextView.font!.lineHeight
            // 创建富文本
            let attributedText = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight) // -4 是试出来的,大了或者小了,都会导致图文不在一行
            
            // 获取当前光标的位置
            let selectedRange = composeTextView.selectedRange
            
            /* 使用 append 或者 insert 功能都不全
            拼接 - 失败
            allAttr.appendAttributedString(attr)
            插入不可变富文本 - 失败
            allAttr.insertAttributedString(attr, atIndex: selectedRange.location)
            */
            
            // 使用 replace
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attributedText)
            // 更改完内容后,整体设置富文本属性  --> 若不设置 ,后面输入比第一个字的字体要小
            allAttr.addAttributes([NSFontAttributeName:composeTextView.font!], range: NSRange(location: 0, length: allAttr.length))
            // 赋值给composetTextView 的富文本属性
            composeTextView.attributedText = allAttr
            // 重写设置composeTextView 的光标位置
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            
            // 输入图片表情后,告知 textView 隐藏占位文字 -> 这个通知已经添加过监听者,而且实现了 占位隐藏,所以这里只要发通知即可,接受通知在自定义 textView中
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            // 同时主动调用textView 的代理方法,改变发布按钮的状态
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
        
    }
    
    //MARK:收到表情键盘删除按钮点击通知,调用的方法
    func emoticonDeleteButtonClick(){
        composeTextView.deleteBackward()
    }
    
    //MARK: 监听到键盘frame 变化,调用的方法
    func keyboardWillChangeFrame(notice: NSNotification){
        // 判断是否为 nil
        guard let userInfo = notice.userInfo else {
            return
        }
        // 获取时间
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        // 通过key 获取endFrame
        let endFrame = userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        // 获取 rect
        let endRect = endFrame.CGRectValue()
        // 更新底部工具条约束
        self.bottomToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(endRect.origin.y - SCREENH)
        }
        
        // 给底部工具条约束变化添加动画效果 --> 为什么老是的是直接用 Double 包装???
        UIView.animateWithDuration(duration.doubleValue) { () -> Void in
            self.bottomToolBar.layoutIfNeeded()
        }
    }
    
    //MARK: 取消按钮点击事件
    func cancelAction(){
        composeTextView.resignFirstResponder()
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: 点击发布按钮
    func sendAction(){
//        updateWeibo()
        // 图片表情 -> 图片描述     "表1234"    "[马到成功]1234"
        // 01 遍历的结果
        // 02 遍历的范围
        // 03 遍历是否停止
        // 定义一个可变的字符串
        var allText = ""
        // 遍历 composeTextView.attibutedText
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) -> Void in
            // 代表输入的是文本附件
            if let att = result["NSAttachment"] as? STAttachment {
                allText += (att.emoticon?.chs ?? "")
            } else {
                // 文字 字符串截取
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                allText += str
            }
        }
        // 发送微博
        pictureView.imageList.count > 0 ? upload(allText) : updateWeibo(allText)
        
        
    }
    
    //MARK: setupNav
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imgName: nil, target: self, action: "sendAction")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    
    //MARK: layz
    // 底部工具条
    private lazy var bottomToolBar: STComposeBottomToolBar = STComposeBottomToolBar()
    // pictureView
    private lazy var pictureView: STComposePictureView = STComposePictureView()
    // textView
    private lazy var composeTextView: STComposeTextView = {
        let text = STComposeTextView()
        text.alwaysBounceVertical = true // 设置滚动方向
        text.placeHolder = "和你的好友,分享你的心情"
        text.font = UIFont.systemFontOfSize(16)
        text.delegate = self
        return text
    }()
    // 导航栏自定义 view
    private lazy var titleView: UILabel = {
        // 用户名字
        let name = STUserAccountViewModel.sharedUserAccountTools.userAccount?.screen_name ?? ""
        let str = "发微博\n\(name)"
        
        // 创建一个富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本
        let range = (str as NSString).rangeOfString(name)
        attr.addAttributes([NSForegroundColorAttributeName: ThemeColor, NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        let lab = UILabel()
        lab.textAlignment = .Center
        lab.numberOfLines = 0
        lab.attributedText = attr
        lab.sizeToFit()
        
        return lab
    }()
    // 自定义表情键盘
    private lazy var emoticonKeyboard: STEmoticonKeyboard = STEmoticonKeyboard()
    
    // 实现 deinit 方法,移除监听者
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

//MARK: 点击底部按钮,调用方法
//打开相册
extension STComposeController{
    
    // 打开相册
    func openAlbulm(){
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self;
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    
    // 切换键盘
    func switchKeyboard(){
        // 如果inputView 为nil, 代表当前键盘为系统键盘
        if composeTextView.inputView == nil {
            //            print("系统键盘")
            composeTextView.inputView = emoticonKeyboard
            bottomToolBar.isEmoticonKeyboard = true
        } else {
            // 代表是自定义键盘
            composeTextView.inputView = nil
            bottomToolBar.isEmoticonKeyboard = false
        }
        // 刷新键盘,否则不会切换
        composeTextView.reloadInputViews()
        // 同时设置 composeTextView成为第一响应者
        composeTextView.becomeFirstResponder()
    }
}

extension STComposeController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //图片选择代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 将图片添加到数组
        pictureView.addImage(image.getImageScale(600))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: UITextViewDelegate
extension STComposeController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // 滚动 textView ,隐藏键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        view.endEditing(true)
    }
}


// MAKR: 发布微博
extension STComposeController {
    // 发布文字微博
    func updateWeibo(status: String){
        STNetworkTools.shardTools.composeUpdate(status, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    // 发布图片微博
    //            let data = UIImagePNGRepresentation(self.composePictureView.imageList.first!)!
    //            formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
    
    // 发送多张图片
    
    func upload(status: String){
        
        STNetworkTools.shardTools.composeUpload(status, imageList: pictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    
    
//    func upload(status: String){
//        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
//        let parameters = [
//            "access_token":STUserAccountViewModel.sharedUserAccountTools.accessToken!,
//            "status":status
//        ]
//        
//        let data = UIImagePNGRepresentation(self.pictureView.imageList.first!)!
//        
//        STNetworkTools.shardTools.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
//            
//            formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
//            }, progress: nil, success: { (_, response) -> Void in
//                
//            }) { (_, error) -> Void in
//        }
//        
//    }

}














